<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use app\common\model\User as UserModel;
use think\Db;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $config = array(
        'partner'=>'2088621781822784',//用不着
        'seller_id'=>'admin@bagepanzi.com',//用不着
        'sign_type'=>'RSA2',// 直接写死了
        'it_b_pay'=>'10m',//用不着
        'md5'=>'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public'=>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyfTohI+hS8lWtgEkgEC3fd1SmDgOo/IVicUzE2A2MzfcxS0Fd0LWybhB2CF8FZpzB/zxXZoAHi459HEykF/QK0fSt1k574mpnT0/Sf8tEAfhN3nvrcUtSdJb+mgbYon3K2rtqm4EPTosM9VrlhpUdffdyYT0vzlQvU6CaMZUjlbbWiDoyGNwQphrOUX3UAkV8jVqaTGMLWQmtDy5ipqzaWczNsyZukRZmNJqVBiEmmtgRc+/hTf9ZCbew+ELXvz0LAX5uiULm9ZKWEWl6u74IKBPnI1SJvs9AyYe9XkgmdLxM98qEym5ZA9UrF3rq+d/sKAAykpnhfNXISYjdkoCwQIDAQAB',
        'public_key'=>"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4FApyqOn6xsypuLZXak+Q+lRjrfdZ2NLeLh7zJwHXljLrq23d4b2u0DRppwjUOrsD5BshQZJOcEJPyZ0dridUBn4T55Lf+9VDgYXFUi96nNR6b0fdrarJTJcwb7a/ZAFXXuVcULoTv98FdLXp1s3r3pYXPqN+0meuh5Tpno0YoI6UEZaEl799CAk0qHNbN4DdvCu5yah45bxjqme5NQDBUxhZO8n07A6WS1f8ctEhIcozJTfLPq6jxsaszPyiZd1QEGi/0sZ29ku1n94fnfAWa+TIJZOlxynqbjo/pExeiEc4dIdi4+e9mg6hr6PV67Me/i85nA56xOGSbLE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EAnseH+E26foqMmOUsTf5pSjZILDwTOSzUcvrTMDlqFGphFxOEWnznyJKwECRSc2g96NUhGl1jbjLtB7cKrKV4N3LKnknR5DPi7fRFonNC78ClU6e4Rnby2n+WlyWIFgwNDzmEGtulQPoparFhDNcEZhmI45y1TzIY+gnJ74xwUA0CgYAH7IAJhq1at+MOAE4Cd5HFy12VCjxc8tkAY3ELk5ebaHVIKeduacM6S5yk3ykHwxISm/jLduwWgJ+Mw2+FHeHvAz5lfdxGKgTrOOFv0GpxUBRbcUYq5I7G1sn6tVsBOeCpQsQ+gRsmeh7E9rhlk+VXBIZEzFWP8l6KPTvk9rp/EQKBgHmB5wjDx2D48GHasMzaCSCYdMICR7Y41gn3U+PYmoznCtDyw3iO+1gudsWmnom/317ntpMMf8pOPnJoP2r8ybJya2YzYX081Vb/mY8U1APoiyDtSr9kBe8s8EOjE/Wgtk70aN9hrY3etNDns5QBLKxciEqntV/2t9Z1t8cxXaTs'
    );
    public function __construct()
    {
        parent::__construct();
        require_once(dirname(__FILE__).'/../conf/errorList.php');
        $this->_error = $PUBLIC_ERROR_LIST;
        header("Content-type:application/json;charset=utf-8");

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value
        header("Access-Control-Allow-Origin:*");

//        return true;
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){return false;}
            $data['user_last_login'] = date('Y-m-d H:i:s',time());
            Db::table('up_u_user')->where('user_id',$uid)->update($data);
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }
    /**
     * 对返回信息的统一处理
     * @param $data 成功需要返回的信息
     * @param $go 是否需要继续对信息进行处理
     * @param $ext 扩展字段数组
     */
    protected function apiSuccess($data = '',$extra = '')
    {
        $info['status'] = '200';
        $info['msg']= '成功';
        if ($data || is_array($data)) {
            $info['data'] = $data;
        }
        if($extra){
            foreach ($extra as $key=>$value){
                $info[$key] = $value;
            }
        }
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
    }

    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    /**
     * @param $client
     * @param $sence
     * @param $orderId
     * @return array|bool
     * 极光推送
     */
    public function Jpush($token,$msg,$type,$msg_data){
        //帮帮
        $ji=array(
            'appKey'=>'8614b01a9733364444c8c7d4',
            'masterSecret'=>'35a4e075f5d1ddcb4b3c25f3',
        );
        $client = new \JPush\Client($ji['appKey'],$ji['masterSecret']);
        $push = $client->push();
        $push->setPlatform('all');
        if($type==1){
            $push->addAlias($token);
        }else{
            $push->addAllAudience();
        }
        $push->iosNotification($msg, array(
                'alert'=>$msg,
                'badge' => '1',
                'extras' => $msg_data,
                'sound'=>'default'
            )
        );
        $push->androidNotification($msg, array(
            'badge' => '1',
            'extras' => $msg_data
        ));
        return $push->send();

    }

    /**
     * @param $phone
     * @param $num
     * @return mixed
     * 创蓝短信
     */
    public function duanxin($phone,$num){
        //帮帮
        $body_json = array(
            'account'=>'N2926691',
            'password'=>'daeMlo112',
            'msg'=>"【帮帮】尊敬的用户，您本次的验证码为{$num}，请于5分钟内正确输入，切勿泄露他人！",
            'phone'=>$phone,
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'http://smssh1.253.com/msg/send/json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json_encode(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }
    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
    function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }


    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no,$money){
//    public function getParam(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest',EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->appId = "2018062260400862";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"会员购买\","
                . "\"subject\": \"会员权限购买\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://mww2.xuanwumobile.com/api/Bendi/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        }catch (\Exception $e){
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    public function checkReturn(){
        import('alipay.aop.AopClient',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            return $_POST;
        }else{
            return false;
        }
    }
}